package com.swak.boot.config.zookeeper.registry;

import java.util.Map;

import org.apache.curator.framework.CuratorFramework;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.ConfigurableEnvironment;

import com.swak.Constants;
import com.swak.OS;
import com.swak.boot.config.zookeeper.ZookeeperBuilder;
import com.swak.boot.config.zookeeper.ZookeeperProperties;
import com.swak.registry.RegistryService;
import com.swak.registry.URL;
import com.swak.utils.Maps;
import com.swak.zookeeper.ZookeeperRegistry;
import com.swak.zookeeper.ZookeeperService;

/**
 * 开启zk 注册发现
 * 
 * @author lifeng
 */
@ConditionalOnClass({ CuratorFramework.class, ZookeeperService.class })
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableZk", matchIfMissing = true)
@EnableConfigurationProperties(ZookeeperProperties.class)
public class ZookeeperRegistryAutoConfiguration {

	/**
	 * 创建服务注册和发现
	 * 
	 * @param service
	 * @return
	 * @throws InterruptedException 
	 */
	@Bean
	@Primary
	public RegistryService zookeeperRegistry(ConfigurableEnvironment environment, ZookeeperProperties properties)
			throws InterruptedException {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Application_KEY, environment.getProperty(Constants.Application_Name));
		URL url = new URL(Constants.Registry_Zookeeper_Key, OS.ip(), 0, parameters);
		return new ZookeeperRegistry(url, ZookeeperBuilder.build(properties));
	}
}
